package com.zzj.utils;

import com.zzj.model.entity.Hospital;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class HtmlParseUtil {

    public List<Hospital> hospitalParams(String url, String page,String location) throws Exception {
        //解析网页
        Document document = Jsoup.parse(new URL(url+"/hospital?page=" + page+"&location="+location), 30000);
        //所有你在js中可以使用的方法 这里都能用
        Element element = document.getElementById("hospitallist");
        //获取所有的li元素
        Elements elements = element.getElementsByClass("tr");
        ArrayList<Hospital> hospitals = new ArrayList<>();
        for (Element el : elements) {
            Hospital hospital = new Hospital();
            hospital.setLogo(el.getElementsByTag("img").eq(0).attr("src"));
            hospital.setHospital(el.getElementsByClass("td").eq(0).text().split(" ")[1]);
            hospital.setProperty(el.getElementsByClass("td").eq(2).text());
            hospital.setType(el.getElementsByClass("td").eq(3).text());
            hospital.setLevel(el.getElementsByClass("td").eq(4).text());
            hospital.setScale(el.getElementsByClass("td").eq(5).text());
            hospital.setEstablishYear(el.getElementsByClass("td").eq(6).text());
            Thread.sleep(500);
            Document d = Jsoup.parse(new URL(url + el.getElementsByTag("a").eq(0).attr("href")+"/detail"), 30000);
            Elements elementsByClass = d.getElementsByClass("pc-hospital-detail");
            Element element1 = elementsByClass.get(0);
            String p = element1.getElementsByTag("p").eq(0).text();
            hospital.setDescription(p);
            String address = element1.getElementsByClass("block").get(1).getElementsByClass("block-body").get(0).getElementsContainingText("机构地址").get(1).getElementsByTag("span").get(1).text();
            hospital.setAddress(address);
            hospitals.add(hospital);
        }
        return hospitals;
    }
}
